<?php

class filemanager extends Module {
	
	public function __construct() {
		parent::__construct(__CLASS__);
	}
	
	public function __default() {
		$folder = trim(getRequest('folder'), '/');
		
		$response = new ModuleResponse;
		$response->setTemplate('filemanager/index');
		
		return $response;
	}
	
	public function js_action() {
		$folder = trim(getRequest('folder'), '/');
		
		if (getRequest('button_upload','bool')) {
			$this->uploadFiles($folder);
		}
		if (getRequest('button_zip','bool')) {
			$this->uploadZip($folder);
		}
		if (getRequest('button_new_folder','bool')) {
			$this->createFolder($folder);
		}
		if (getRequest('button_delete','bool')) {
			$this->deleteFiles($folder);
		}
		if (getRequest('button_rename','bool')) {
			$this->renameFile($folder);
		}
		if (getRequest('button_perms','bool')) {
			$this->savePerms($folder);
		}		
	}
	
	public function ajax_files() {
		$this->setResponseFormat('xml');
		
		$response = new ModuleResponse;
		$response->addObject(FilesController::getFolder(DOC_ROOT . '/' . trim(getRequest('folder'), '/')));
		
		return $response;
	}
	
	private function savePerms($folder) {
		$addPath = $folder == '' ? '' : '/' . $folder;
		
		$path = DOC_ROOT . $addPath . '/' . getRequest('name');
		
		if (!file_exists($path) || getRequest('perms') == '') {
			$this->flush('<script type="text/javascript">parent.filemanagerPermsError();</script>');
		}
		
		umask(0000);
		chmod($path, getRequest('perms'));
		
		$this->flush('<script type="text/javascript">parent.filemanagerPermsSaved();</script>');
	}
	
	private function renameFile($folder) {
		$addPath = $folder == '' ? '' : '/' . $folder;
		
		$old = isset($_POST['old_name']) ? $_POST['old_name'] : '';
		$new = isset($_POST['new_name']) ? $_POST['new_name'] : '';
		
		if ($old == '' || $new == '') {
			$this->flush('<script type="text/javascript">parent.filemanagerRenameError();</script>');
		}
		
		$oldPath = DOC_ROOT . $addPath . '/' . $old;
		$newPath = DOC_ROOT . $addPath . '/' . $new;
		
		if (!file_exists($oldPath) || file_exists($newPath)) {
			$this->flush('<script type="text/javascript">parent.filemanagerRenameError();</script>');
		}
		
		rename($oldPath, $newPath);
		
		$this->flush('<script type="text/javascript">parent.filemanagerRenamed();</script>');
	}
	
	private function deleteFiles($folder) {
		$addPath = $folder == '' ? '' : '/' . $folder;
		
		if (isset($_POST['delete']) && is_array($_POST['delete'])) {
			$aFiles = $_POST['delete'];
		} else {
			$aFiles = array();
		}
		
		foreach ($aFiles as $filename) {
			FilesController::getFile(DOC_ROOT . $addPath . '/' . $filename)->delete();
		}
		
		$this->flush('<script type="text/javascript">parent.filemanagerFilesDeleted();</script>');
	}
	
	private function createFolder($folder) {
		$addPath = $folder == '' ? '' : '/' . $folder;
		$newName = getRequest('folder_name');
		
		$path = DOC_ROOT . $addPath . '/' . $newName;
		
		if (!mkdir($path)) {
			$this->flush('<script type="text/javascript">parent.filemanagerFolderExists();</script>');
		}
		
		$this->flush('<script type="text/javascript">parent.filemanagerFolderCreated();</script>');
	}
	
	private function uploadFiles($folder) {
		$addPath = $folder == '' ? '' : '/' . $folder;
		
		if (!isset($_FILES['upload'])) {
			$this->flush('<script type="text/javascript">parent.filemanagerUploadError();</script>');
		}
		
		$cnt = count($_FILES['upload']['name']);
		$aFiles = array();
		
		foreach ($_FILES['upload'] as $key => $values) {
			$i = 0;
			
			foreach ($values as $value) {
				$aFiles[$i][$key] = $value;
				++$i;
			}			
		}
		
		foreach ($aFiles as $fileData) {
			if ($fileData['name'] == '') {
				continue;
			}
			
			$path = DOC_ROOT . $addPath . '/' . $fileData['name'];
			
			FilesController::uploadFile($fileData, $path);
		}
		
		$this->flush('<script type="text/javascript">parent.filemanagerFilesUploaded();</script>');
	}
	
	private function uploadZip($folder) {
		include ENGINE_ROOT . '/libs/pclzip.lib.php';
		
		$addPath = $folder == '' ? '' : '/' . $folder;
		
		if (!isset($_FILES['zip']) || $_FILES['zip']['name'] == '') {
			$this->flush('<script type="text/javascript">parent.filemanagerZipError();</script>');
		}
		
		$zipFilename = ENGINE_ROOT .  '/temp/filemanager_upload.zip';
		
		FilesController::uploadFile($_FILES['zip'], $zipFilename, true);
		
		$zip = new PclZip($zipFilename);
		
		$list = $zip->listContent ();
		
		if (!$list) {
			$this->flush('<script type="text/javascript">parent.flushError("Zip error: ' . $zip->errorInfo (true) . '");</script>');
		}
		
		foreach ($list as $item) {
			$filename = DOC_ROOT . $addPath . '/' . trim ($item['filename'], '/');
			
			if ($item['folder']) {
				if (!is_dir ($filename)) {
					mkdir ($filename);
					if (!is_writable ($filename)) {
						chmod ($filename, 0777);
					}
				}
			} else {
				if (file_exists ($filename)) {
					if (!is_writable ($filename)) {
						chmod ($filename, 0777);
					}
					
					$listContent = $zip->extract (PCLZIP_OPT_BY_NAME, $item['stored_filename'], PCLZIP_OPT_EXTRACT_AS_STRING);
					
					if (count ($listContent)) {
						file_put_contents($filename, $listContent[0]['content']);
					}
				} else {
					$zip->extract (PCLZIP_OPT_BY_NAME, $item['stored_filename'], PCLZIP_OPT_ADD_PATH, DOC_ROOT . '/' . $folder);
				}
			}
		}
		
		unlink($zipFilename);
		
		$this->flush('<script type="text/javascript">parent.filemanagerZipUploaded();</script>');
	}
	
}